package com.wecommodule.bpm.ext.framework.config.support;

import com.wecommodule.bpm.ext.framework.common.entity.ResponseResult;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 *
 */
public class ExceptionHandlerSupport {
    @ExceptionHandler(Exception.class)
    @Order
    @NotNull
    public ResponseResult handleException(@NotNull Exception ex, @NotNull WebRequest request) throws Exception {
        ex.printStackTrace();
        return ResponseResult.errorResponse("发生未知异常");
    }


    @ExceptionHandler(DataAccessException.class)
    @Order(0)
    @NotNull
    public ResponseResult handleDataAccessException(@NotNull Exception ex, @NotNull WebRequest request) throws Exception {
        ex.printStackTrace();
        DataAccessException dataAccessException = (DataAccessException) ex;
        if (dataAccessException instanceof OptimisticLockingFailureException){
            return ResponseResult.errorResponse("数据库访问异常", HttpServletResponse.SC_CONFLICT);
        }else {
            return ResponseResult.errorResponse("数据库锁异常");
        }
    }
}
